package com.eportal.service.impl;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.dao.SysrolesEntityMapper;
import com.eportal.domain.Sysopt;
import com.eportal.domain.Sysroles;
import com.eportal.domain.SysrolesTemplate;
import com.eportal.entity.SysrolesEntity;
import com.eportal.service.SysRolesService;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * 角色管理业务逻辑接口实现
 */
@Service("sysRolesService")
public class SysRolesServiceImpl implements SysRolesService {

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(SysRolesServiceImpl.class.getName());

	@Resource(name="dao")
	private BaseDAO dao;

	@Resource
	private SysrolesEntityMapper sysrolesDao;

    @Override
    public List<Sysroles> list(JqGridPager jqGridPager, String sql) {
        return dao.query(sql, jqGridPager);
    }

    @Override
    public List<Sysroles> list(String where) {
    	List<Sysroles> list= null;
    	if (where == null) {
    		list = dao.query(" from Sysroles");
		}else{
			list = dao.query(" from Sysroles "+where);
		}
    	return list;
    }

    @Override
    public Sysroles add(Sysroles role) throws Exception {
    	dao.save(role);
        return role;
    }

    @Override
    public void delete(Long id) {
    	Sysroles role = (Sysroles) dao.getById(Sysroles.class, id);
    	dao.delete(role);
    }

    @Override
    public void delete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    public Sysroles get(Long sid) {
        return (Sysroles) dao.getById(Sysroles.class, sid);
    }

    @Override
    public void update(Sysroles role) throws Exception {

        dao.update(role);
    }

	@Override
	public Sysroles getRoleByName(Sysroles role) {
		StringBuilder where = new StringBuilder(" where 1=1 ");
    	where.append("and rName ='");
    	where.append(role.getrName());
    	where.append("' ");
    	where.append("and rAgtent ='");
    	where.append(role.getrAgtent());
    	where.append("' ");
    	where.append("and rCommunity ='");
    	where.append(role.getrCommunity());
    	where.append("' ");
    	List<Sysroles> sysroles = list(where.toString());
    	if(sysroles != null && sysroles.size()>0){
    		return sysroles.get(0);
    	}else{
    		return null;
    	}
	}

	/**
	 * 修改超管角色权限
	 */
	@Override
	public void updateAllManagerRole(SysrolesTemplate sysrolesTemplate, String mListBefore) {
		//比较出模板前后的变化
		String[] mListBefore1 =  mListBefore.split("\\|");
		String[] mlistNow = sysrolesTemplate.getmList().split("\\|");
		List<String> addList = compare(mListBefore1,mlistNow);
		List<String> delList =  compare(mlistNow,mListBefore1);

		String addMList = "";
		if(addList.size()>0){
			addMList = org.apache.commons.lang.StringUtils.join(addList.toArray(),"|");
		}
		String add = "|"+addMList;

		//删除
		if (delList.size()>0) {
			StringBuilder where = new StringBuilder();
			//查询出所有的本级别的管理员
			if("1".equals(sysrolesTemplate.getTmpType())){
				where.append("where rLevel = 1 ");//合作方
			}else if("2".equals(sysrolesTemplate.getTmpType())){
				where.append("where rLevel = 2 ");//社区
			}else{
				where.append("where rLevel = 3 ");//锁厂

			}
			List<Sysroles> sysroles = list(where.toString());
			if(sysroles.size()>0){
				for (Sysroles sysrole : sysroles) {
					//删除
					if (delList.size()>0) {
						if(StringUtils.isBlank(sysrole.getmList())){
							continue;
						}
						String mlistDelNow = deleteMenu(sysrole.getmList(),delList);
						sysrole.setmList(mlistDelNow);
					}
					dao.update(sysrole);
				}
			}
		}
		if (!StringUtils.isBlank(addMList)) {
			StringBuilder where = new StringBuilder();
			//查询出所有的适用了此模板的超级管理员
			where.append(" where isAdmin='1' ");
			if("1".equals(sysrolesTemplate.getTmpType())){
				where.append("and rLevel = 1 ");//合作方
			}else if("2".equals(sysrolesTemplate.getTmpType())){
				where.append("and rLevel = 2  ");//社区
			}else{
				where.append("and rLevel = 3  ");//锁厂
			}
			List<Sysroles> sysroles = list(where.toString());
			if(sysroles.size()>0){
				for (Sysroles sysrole : sysroles) {
					//增加
					if (!StringUtils.isBlank(addMList)) {
						sysrole.setmList(sysrole.getmList()+add);
					}
					dao.update(sysrole);
				}
			}
		}



//		StringBuilder sb  = new StringBuilder("update sysroles set mlist ='");
//		sb.append(sysrolesTemplate.getmList());
//		sb.append("' ");
//		sb.append("where isadmin='1' ");
//		if("1".equals(sysrolesTemplate.getTmpType())){
//			sb.append("and rcommunity == '0'");
//			dao.excute(sb.toString());
//		}else if("2".equals(sysrolesTemplate.getTmpType())){
//			sb.append("and rcommunity != '0'");
//			dao.excute(sb.toString());
//		}
	}

	private String deleteMenu(String mlist, List delList) {
		String[] mListBefore =  mlist.split("\\|");
		List<String> listBefore = Arrays.asList(mListBefore);
		List<String> arrayListBefore = new ArrayList<String>(listBefore);
		List<String> arrayListDel = new ArrayList<String>(delList);
		arrayListBefore.removeAll(arrayListDel);
		String mList = org.apache.commons.lang.StringUtils.join(arrayListBefore.toArray(),"|");
		return mList;
	}

	public static List<String> compare(String[] t1, String[] t2) {
	    List<String> list1 = Arrays.asList(t1);
	    List<String> list2 = new ArrayList<String>();
	    for (String t : t2) {
	      if (!list1.contains(t)) {
	        list2.add(t);
	      }
	    }
	    return list2;
	}


	/**
     * 角色新增保存方法
     * @throws IOException
     */
	@Override
    @LogAnnotation(operateDescribe="角色新增")
    public Map<String, Object> addMethod(Sysroles role){
		try {
			String msg = ValidateUtil.validate(role);
	        if (msg == null || msg.trim().length() == 0) {
	            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
	            	role.setrAgtent(user.getAgtCode());
	            	role.setrCommunity(user.getCommunityId());
	            	role.setIsAdmin("0");
	            	role.setUserName(Long.toString(user.getSid()));
	            	role.setOptTime(new Timestamp(System.currentTimeMillis()));
	            	role =  add(role);
	                result.put("code", 1);
	                result.put("msg", "操作成功");
	                result.put("objectId", role.getSid());
	        } else {
	            result.put("code", 0);
	            result.put("msg", msg);
	        }
		} catch (Exception e) {
			log.error("角色保存失败", e);
			result.put("code", 0);
			result.put("msg", "操作失败");
		}
        return result;
    }

	 /**
     * 角色修改保存方法
     */
	@Override
    @LogAnnotation(operateDescribe="角色修改")
    public Map<String, Object> updateMethod(Sysroles role) {
		try {
	        String msg = ValidateUtil.validate(role);
	        result.put("objectId", role.getSid());
	        if (msg == null || msg.trim().length() == 0) {
	            	if (!ifHasRole(role.getSid())) {
	           		 	result.put("code", 0);
	                    result.put("msg", "没有权限");
	                    return result;
					}
	            	Sysroles entity = get(role.getSid());
	            	entity.setrName(role.getrName());
	            	entity.setrLevel(role.getrLevel());
	            	entity.setStatus(role.getStatus());
	            	entity.setmList(role.getmList());
	                update(entity);
	                result.put("code", 1);
	                result.put("msg", "操作成功");
	        } else {
	            result.put("code", 0);
	            result.put("msg", msg);
	        }
		} catch (Exception e) {
			log.error("角色更新失败", e);
			result.put("code", 0);
			result.put("msg", "操作失败");
		}
        return result;
    }
	@Override
	/**
     * 角色删除方法,主要用于切面记录操作日志
     */
    @LogAnnotation(operateDescribe="角色删除")
    public Map<String, Object> deleteMethod(String param_ids) {
        try {
            List<Long> ids = new LinkedList<Long>();
            result.put("objectId", param_ids);
            for (String s : param_ids.split(",")) {
            	if (!ifHasRole(Long.parseLong(s))) {
           		 	result.put("code", 0);
                    result.put("msg", "没有权限");
                    return result;
				}
                ids.add(Long.parseLong(s));
            }
            delete(ids);
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("角色删除失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
    }
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	 /**
     * 判断角色是否属于该用户管理
     */
    private boolean ifHasRole(Long sid) {
    	Sysroles sysrole = get(sid);
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	//平台超级管理员
    	if(userRole==1){
    		return true;
    	}
    	//是否属于内部角色
    	if(sysrole.getrAgtent().equals(user.getAgtCode()) && sysrole.getrCommunity().equals(user.getCommunityId())){
    		return true;
    	}
    	if(userRole==2){
    		//平台普通管理员可以管理合作方超级管理员角色
    		if("1".equals(sysrole.getIsAdmin()) && sysrole.getrLevel()==1){
    			return true;
    		}
    	}
    	//合作方超级管理员可以管理社区超级管理员角色
    	if(userRole == 3){
    		if(sysrole.getrAgtent().equals(user.getAgtCode()) && "1".equals(sysrole.getIsAdmin()) && sysrole.getrLevel()==2){
    			return true;
    		}
    	}
    	return false;
	}


//todo ---------------------------------------------------------------------------------------


	/**
	 * 角色管理列表接口
	 *
	 * @param pageEntity 分页对象
	 * @param rname
	 * @param rlevel
	 * @param user       当前用户
	 * @param userRole   当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/18 下午5:33
	 */
	@Override
	public PageInfo<SysrolesEntity> queryForPage(PageEntity pageEntity, String rname, String rlevel, Sysopt user, int userRole) {
		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();//驼峰命名-->下划线（对应数据库字段）
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}

		List<SysrolesEntity> list = sysrolesDao.queryForList(rname,rlevel,user,userRole);
		return new PageInfo<>(list);
	}

}
